package com.aaa.bookproject.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.HashMap;

/**
 * @author ：YongQi Lv
 * @date ：2021/4/23 20:40
 */
@Configuration
public class ShiroConfig {

    public static final String ANON="anon";
    /**
     * auchc 需要登录才可以访问的权限
     */
    public static final String AUTHC="authc";
    public static final String ROLES="roles[admin]";
    public static final String MENUS="perms[userquery,setting]";


    /**
     * 用户领域
     * @return
     */
    @Bean("userRealm")
    public UserRealm getRealm(){
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }

    /**
     * 安全管理者
     * @param userRealm
     * @return
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        // 默认的Web安全管理者对象获取securityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 将userRealm其中
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 过滤器，在项目服务器启动的时候，就率先执行此方法
     * @param securityManager
     * @return
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilter(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        // 获取实例化对象
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 将securityManager摄入
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 创建map配置需要添加自定义的前后端分离的拦截器
        HashMap<String, Filter> map = new HashMap<>();
        map.put(AUTHC,new LoginFilter());
        // 将我们设置的map内容添加到过滤器中
        shiroFilterFactoryBean.setFilters(map);
        return shiroFilterFactoryBean;
    }

    /**
     * 在自定义过滤器的时候，需要定义的方法
     * FilterRegistrationBean理解为web.xml
     * DelegatingFilterProxy：理解为再web.xml文件中配置了一个过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean<DelegatingFilterProxy> filterRegistrationBean(){
        FilterRegistrationBean<DelegatingFilterProxy> bean=new FilterRegistrationBean<>();
        DelegatingFilterProxy delegatingFilterProxy=new DelegatingFilterProxy();
        bean.setFilter(delegatingFilterProxy);
        bean.addUrlPatterns("/**");
        bean.addInitParameter("targetFilterLifecycle","true");
        bean.addInitParameter("targetBeanName","shiroFilterFactoryBean");
        return bean;
    }
}
